/*
* Copyright (C) 2010-2012 Magnus Skjegstad
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
* 
* The latest version of this library can be downloaded from http://mist-pubsub.googlecode.com
* 
*/
package com.skjegstad.mist2.demos;

import com.skjegstad.mist2.MistCoreManager;
import com.skjegstad.mist2.exceptions.MistException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

/**
 *
 * @author Magnus Skjegstad
 */
public class TestMistInputPipe {
    public static void main(String[] argv) throws UnknownHostException, IOException, MistException, InterruptedException {

        BufferedInputStream inputPipe = new BufferedInputStream(System.in, 63000);
        
        MistCoreManager mist = new MistCoreManager();
        //mist.enableBroadcast(InetAddress.getByName("10.0.0.255"), 1234);
        mist.enableMulticast(InetAddress.getByName("224.0.0.1"), 1234);

        mist.setDebug(false);
        mist.start();

        int read = 0;
        int frag = 0;
        long start = System.currentTimeMillis();
        long sentSoFar = 0;
        while (read > -1) {
            byte[] input = new byte[63000];
            read = inputPipe.read(input);

            if (read == -1)
                continue;

            ByteBuffer b = ByteBuffer.allocate(read + 4);
            
            b.putInt(frag++);
            b.put(input, 0, read);

            sentSoFar = sentSoFar + b.array().length;
            double bw = sentSoFar / (double)((System.currentTimeMillis() - start) / 1000.0);
            System.out.println("Sending " + b.array().length + " bytes from stdin, bw="+bw);


           // System.err.println("before");
            mist.publish("no.ffi.stream.test", b.array(), 30000);
           // System.err.println("after");
            //Thread.sleep(1000);
        }

        System.out.println("End of stream. Shutting down in 10 sec.");

        Thread.sleep(10000);

        mist.stop();
    }


}
